package com.zhku.shoppingspringboot.config;


import com.zhku.shoppingspringboot.common.RedisCacheManagerResolver;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 作者：zjy
 * 时间：2024/3/18 9:18
 * 描述:无bug
 */
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory connectionFactory){
        RedisTemplate<Object,Object> redisTemplate=new RedisTemplate<>();
        //默认的key序列化器：jdkSerializationRedisSerialiazation,现在将他更改为StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory,
                                     RedisCacheConfiguration defaultCacheConfiguration,
                                     Map<String, RedisCacheConfiguration> cacheConfigurationMap) {
        // Create and configure a custom RedisCacheManagerResolver
        RedisCacheWriter cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(
                redisConnectionFactory);

        return new RedisCacheManagerResolver(cacheWriter,
                defaultCacheConfiguration, cacheConfigurationMap);
    }
    @Bean
    public RedisCacheConfiguration defaultCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30));
    }


    @Bean
    public Map<String, RedisCacheConfiguration> cacheConfigurationMap() {
        return new LinkedHashMap<>();
    }


}
